<?php

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Middleware\AdminMiddleware;
use App\Model\AdminMenu;
use App\Service\ToolService;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;

#[Controller(prefix: '/admin/Menu'), Middleware(AdminMiddleware::class)]
class MenuController extends BaseController {

    /**
     * 获取菜单列表
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'index')]
    public function index(): array {
        $keywords = $this->request->query('keywords', '');
        $obj = AdminMenu::query();
        if ($keywords) {
            $obj = $obj->where('title', 'like', "%{$keywords}%");
        }
        $obj = $obj->orderBy('sort')->get();
        $list = ToolService::buildArrFromObj($obj);
        if (!$keywords) {
            $list = ToolService::listToTree($list);
        }

        return $this->buildSuccess([
            'list' => $list
        ]);
    }

    /**
     * 新增菜单
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[PostMapping(path: 'add')]
    public function add(): array {
        $postData = $this->request->post();
        if ($postData['url']) {
            $postData['url'] = 'admin/' . $postData['url'];
        }
        $updateData = $this->filterData((new AdminMenu())->getTable(), $postData);
        $res = AdminMenu::insert($updateData);
        if ($res === false) {
            return $this->buildFailed(ErrorCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }

    /**
     * 菜单状态编辑
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'changeStatus')]
    public function changeStatus(): array {
        $id = $this->request->query('id', 0);
        $status = $this->request->query('status', 0);
        AdminMenu::query()->where('id', $id)->update(['show' => $status]);

        return $this->buildSuccess();
    }

    /**
     * 编辑菜单
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[PostMapping(path: 'edit')]
    public function edit(): array {
        $postData = $this->request->post();
        if ($postData['url']) {
            $postData['url'] = 'admin/' . $postData['url'];
        }

        $updateData = $this->filterData((new AdminMenu())->getTable(), $postData);
        AdminMenu::query()->where('id', $postData['id'])->update($updateData);

        return $this->buildSuccess();
    }

    /**
     * 删除菜单
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'del')]
    public function del(): array {
        $id = $this->request->query('id');
        if (!$id) {
            return $this->buildFailed(ErrorCode::EMPTY_PARAMS, '缺少必要参数');
        }

        $id = explode(',', $id);
        AdminMenu::query()->whereIn('id', $id)->delete();

        return $this->buildSuccess();
    }

}
